package activity.personal;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.itboye.hutoubenjg.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import base.BaseActivity;
import base.MyApplcation;
import presenter.UserPresenter;
import util.utls.ByAlert;
import util.utls.CameraPopupWindow;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.MultipartRequest;
import util.utls.SPUtils;
import util.volley.ResultEntity;

/**
 * 认证信息xi
 * <p>
 * <p>
 * Created by itboye on 2016/12/6.
 */

public class ActivityMasterCertificate extends BaseActivity implements Observer{
    EditText driver_name, driver_code;
    TextView tvTitle;
    ImageView back;
    TextView ok;
    ImageView update_up,update_down;//身份证正面，背面

    /** 使用相机拍照（正面） */
    private static final int REAL_PHONE = 1;
    /** 使用相机拍照（背面） */
    private static final int REAL_PHONE_TWO = 3;
    /** 身份证正面的选择 */
    private String localSelectPath01;
    /** 身份证背面的选择 */
    private String localSelectPath02;
    /** 驾驶证*/
    private String localSelectPath03;
    private String type;
    ImageView real_img01, real_img02,real_img03;
    private String fileName01;

    CameraPopupWindow mCameraPopupWindow;

    String zhengID,fanID;//正面图片上传成功之后的Id,反面id，驾驶证id

    UserPresenter presenter;
    String uid;
    TextView tvMasterUp,tvMasterdown;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_master_certificate);
        tvTitle.setText("师傅认证");
//        tvTest.setVisibility(View.GONE);
        presenter=new UserPresenter(this);
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    private String picture_name;
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REAL_PHONE:// 相机
                    String sdStatus = Environment.getExternalStorageState();
                    if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                        Log.i("TestFile",
                                "SD card is not avaiable/writeable right now.");
                        return;
                    }
                    picture_name = android.text.format.DateFormat.format(
                            "yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
                            + ".jpg";
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
                    // SavePicInLocal(bitmap);
                    FileOutputStream b = null;
                    File file = new File("/sdcard/Image/");
                    file.mkdirs();// 创建文件夹
                    fileName01 = "/sdcard/Image/" + picture_name;

                    try {
                        b = new FileOutputStream(fileName01);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            b.flush();
                            b.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    Bitmap bit = BitmapFactory.decodeFile(fileName01);
                    if (type != null) {
                        if (type.equals("zheng")) {
                            localSelectPath01 = fileName01;
                            onImage(localSelectPath01);
                            update_up.setImageBitmap(bit);
                            tvMasterUp.setVisibility(View.GONE);
                        }else if (type.equals("fan")) {
                            localSelectPath02 = fileName01;
                            onImage(localSelectPath02);
                            update_down.setImageBitmap(bit);
                            tvMasterdown.setVisibility(View.GONE);
                        }
                    }

                    mCameraPopupWindow.dismiss();
                    break;

                case REAL_PHONE_TWO:// 相册
                    /**
                     * 当选择的图片不为空的话，在获取到图片的途径
                     */
                    Uri selectedImage04 = data.getData();
                    String innerUrl = getRealPathFromURI(selectedImage04);
                    if (type != null) {
                        if (type.equals("zheng")) {
                            localSelectPath01 = innerUrl;
                            onImage(localSelectPath01);
                        }else if (type.equals("fan")) {
                            localSelectPath02 = innerUrl;
                            onImage(localSelectPath02);

                        } else {
                            localSelectPath03 = innerUrl;
                            onImage(localSelectPath03);
                        }
                    }

                    Bitmap bt04 = BitmapFactory.decodeFile(innerUrl);
                    if (type != null) {
                        if (type.equals("zheng")) {
                            update_up.setImageBitmap(bt04);
                            tvMasterUp.setVisibility(View.GONE);// 把图片显示在ImageView控件上
                        } else if (type.equals("fan")) {
                            update_down.setImageBitmap(bt04);
                            tvMasterdown.setVisibility(View.GONE);
                        }
                    }
                    mCameraPopupWindow.dismiss();
                    break;

                default:
                    break;
            }
        }

    }
    public void onImage(String str) {
        showProgressDialog("上传中....", true);
        File files = new File(str);
        if (str == null) {
            ByAlert.alert("请上传图片");
            return;
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("uid", IsUtilUid.isUid());
        String leixing="";
        if(type.equals("jia")){
            leixing="driver_cert";
        }else{
            leixing="id_certs";
        }
        params.put("type", leixing);

        MultipartRequest multipartRequest = new MultipartRequest(
                Const.IMAGE_URL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String arg0) {
                        Log.d("urlTime", arg0.toString());

                        allInfoFromJson(arg0.toString());

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                ByAlert.alert(arg0);
            }
        }, "image", files, params);
        MyApplcation.addRequest(multipartRequest);

    }
    public void allInfoFromJson(String jsonStr) {

        try {
            JSONArray jsonArray = new JSONObject(jsonStr).getJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                if(type.equals("zheng")){
                    zhengID=jsonObject.getString("id");
                }else if(type.equals("fan")){
                    fanID=jsonObject.getString("id");
                }
                String busName = jsonObject.getString("id");
                Log.d("busLin", busName);
                String time = String.valueOf((int) (Math.random() * 10));
                ByAlert.alert("上传成功!");
                try {
                    closeProgressDialog();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.update_up:
                type = "zheng";
                mCameraPopupWindow = new CameraPopupWindow(this, onclicklister01);
                mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.update_down:
                type = "fan";
                mCameraPopupWindow = new CameraPopupWindow(this, onclicklister01);
                mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;

            case R.id.ok:
//                intent=new Intent(this,RenZhengInformationActivity.class);
//                startActivity(intent);
                uid = (String) SPUtils.get(this, null, Const.ID, "");
                String name=driver_name.getText().toString();
                String code=driver_code.getText().toString();
                if(name.equals("")){
                    ByAlert.alert("请输入真实姓名");
                    return;
                }
                if(code.equals("")){
                    ByAlert.alert("请输入身份证号码");
                    return;
                }
                if(zhengID.equals("")){
                    ByAlert.alert("请先上传身份证");
                    return;
                }
                if(fanID.equals("")){
                    ByAlert.alert("请先上传身份证");
                    return;
                }

                StringBuffer sb=new StringBuffer();
                sb.append(zhengID+",");
                sb.append(fanID+",");
                showProgressDialog("请稍后...", true);
                presenter.sijiRenZheng(uid,name,code,sb.toString());
                //发送广播改变认证信息
                Intent intent1=new Intent("IsAuth");
                sendBroadcast(intent1);
                break;
        }
    }
    /**
     * 正面
     */
    private View.OnClickListener onclicklister01 = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.open_camera:
                    /**
                     * 打开照相机
                     */
                    String state = Environment.getExternalStorageState();
                    if (state.equals(Environment.MEDIA_MOUNTED)) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, REAL_PHONE);

                    } else {
                        ByAlert.alert("请确认已经插入SD卡");
                    }
                    break;
                case R.id.pick_image:
                    Intent intent2 = new Intent();
                    intent2.setType("image/*");// 可选择图片视频
                    // 修改为以下两句代码
                    intent2.setAction(Intent.ACTION_PICK);
                    intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
                    startActivityForResult(intent2, REAL_PHONE_TWO);
                    break;
                default:
                    break;
            }
        }
    };
    /**
     * 该方法用于获取文件的真实路径从URI 从相机拍摄
     */
    private String getRealPathFromURI(Uri contentUri) {
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = this.managedQuery(contentUri, proj, null, null,
                    null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity=handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if(entity.getEventType()==UserPresenter.renzheng_success){
                ByAlert.alert(entity.getData());
                finish();

            }else if(entity.getEventType()==UserPresenter.renzheng_fail){
                ByAlert.alert(entity.getData());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }
}
